<?php

namespace app\admin\controller;

use app\admin\model\agent\Info;
use app\admin\model\house\Auth;
use app\admin\model\house\In;
use app\admin\model\Preproduct;
use app\admin\model\Supplier;
use app\admin\model\Wxpro;
use app\common\controller\Backend;
use fast\Random;
use think\addons\Service;
use think\Cache;
use think\Config;
use think\console\command\make\Model;
use think\Db;
use think\Lang;
use app\admin\model\halt\Cate;
use app\admin\model\Githouse;
use qrcodeq\QrReader;
/**
 * Ajax异步请求接口
 * @internal
 */
class Ajax extends Backend
{

    protected $noNeedLogin = ['lang'];
    protected $noNeedRight = ['*'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();

        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);
    }

    /**
     * 加载语言包
     */
    public function lang()
    {
        header('Content-Type: application/javascript');
        $controllername = input("controllername");
        //默认只加载了控制器对应的语言名，你还根据控制器名来加载额外的语言包
        $this->loadlang($controllername);
        if($controllername != 'auth.admininfo'){
            $this->loadlang('finance.extract.week');
        }
        return jsonp(Lang::get(), 200, [], ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
    }
    //问答同步数据到redis
    public function asyncque($ids){
        $id = intval($ids);

        $manager    = new \MongoDB\Driver\Manager('mongodb://127.0.0.1:27017');
        $bulk = new \MongoDB\Driver\BulkWrite();
        $keys='volueme_'.$ids;
        $bulk->delete(array('keys' => $keys));
        $vInfo = Db::name('ques_volume')->find($id);
        $info = Db::name('ques_volume_subject')->field('id,volume_id,name,type,must_fil')->order('weigh asc,id asc')->where('volume_id',$id)->select();
        $returnData=array();
        foreach($info as $v){
            $datas = Db::name('ques_volume_subject_data')->where('subject_id',$v['id'])->select();
            $v['timu']=$datas;
            $returnData[]=$v;
        }
        $vInfo['subject']=$returnData;
        if ($vInfo['status_school']==2){
            $school = Db::name('ques_volume_school')->order('weigh asc,id asc')->where('volume_id',$id)->select();
            $vInfo['school']=$school;

        }

        $dataInfo = json_encode($vInfo);
        $redis=$this->gRedis();
        $redis->set('nums',1);
        $bulk->insert(array(
            'keys'=>$keys,
            'val'=>$dataInfo
        ));
        $result = $manager->executeBulkWrite('db.volume', $bulk);

        $this->success('同步成功');


    }
    private function gRedis(){
        try{
            $redis = new \Redis();
            $redis->connect('127.0.0.1', 6379);//serverip port
            $redis->select(1);
            return $redis;
            //抛出异常
        } catch (Exception $e) {
            echo $e->getMessage();
            // die(); // 终止异常
        }

    }
    /**
     * 上传文件
     */
    public function upload($typeStatus=0,$pay=null)
    {
        
        Config::set('default_return_type', 'json');
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }
       
        //判断是否已经存在附件
        $sha1 = $file->hash();

        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //验证文件后缀
        if ($upload['mimetype'] !== '*' &&
            (
                !in_array($suffix, $mimetypeArr)
                || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
            )
        ) {
            $this->error(__('Uploaded file format is limited'));
        }
        $replaceArr = [
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{day}'      => date("d"),
            '{hour}'     => date("H"),
            '{min}'      => date("i"),
            '{sec}'      => date("s"),
            '{random}'   => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}'   => $suffix,
            '{.suffix}'  => $suffix ? '.' . $suffix : '',
            '{filemd5}'  => md5_file($fileInfo['tmp_name']),
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //
        $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $params = array(
                'admin_id'    => (int)$this->auth->id,
                'user_id'     => 0,
                'userid'     => $this->auth->userid,
                'username'     => $this->auth->username,
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);
           if($typeStatus){
                $url = $this->analysis($uploadDir . $splInfo->getSaveName());
                if (!$url) {
                    $this->error(__('二维码识别失败'));
                }
                if($pay == 'alipay' && strpos ($url,'ALIPAY.COM') === false) {
                     $this->error(__('请上传正确的支付宝收款码'));
                }elseif ($pay == 'qq' && strpos($url,'qianbao.qq') === false) {
                     $this->error(__('请上传正确的QQ收款码'));
                
                }elseif ($pay == 'wechat' && strpos($url,'wxp://') === false) {
                    $this->error(__('请上传正确的微信收款码'));
                }
                $this->success(__('Upload successful'), null, [
                    'url' => $url
                ]);
            }
            $this->success(__('Upload successful'), null, [
                'url' => $uploadDir . $splInfo->getSaveName()
            ]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }
     /**
     * 解析二维码
     * @return [type] [description]
     */
    private function analysis($file){
        $QrReader =  new QrReader($file);
        return $QrReader->text();
    }
    /**
     * 通用排序
     */
    public function weigh()
    {
        //排序的数组
        $ids = $this->request->post("ids");
        //拖动的记录ID
        $changeid = $this->request->post("changeid");
        //操作字段
        $field = $this->request->post("field");
        //操作的数据表
        $table = $this->request->post("table");
        //排序的方式
        $orderway = $this->request->post("orderway", 'strtolower');
        $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
        $sour = $weighdata = [];
        $ids = explode(',', $ids);
        $prikey = 'id';
        $pid = $this->request->post("pid");
        //限制更新的字段
        $field = in_array($field, ['weigh']) ? $field : 'weigh';

        // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
        if ($pid !== '') {
            $hasids = [];
            $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field('id,pid')->select();
            foreach ($list as $k => $v) {
                $hasids[] = $v['id'];
            }
            $ids = array_values(array_intersect($ids, $hasids));
        }

        //直接修复排序
        $one = Db::name($table)->field("{$field},COUNT(*) AS nums")->group($field)->having('nums > 1')->find();
        if ($one) {
            $list = Db::name($table)->field("$prikey,$field")->order($field, $orderway)->select();
            foreach ($list as $k => $v) {
                Db::name($table)->where($prikey, $v[$prikey])->update([$field => $k + 1]);
            }
            $this->success();
        } else {
            $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
            foreach ($list as $k => $v) {
                $sour[] = $v[$prikey];
                $weighdata[$v[$prikey]] = $v[$field];
            }
            $position = array_search($changeid, $ids);
            $desc_id = $sour[$position];    //移动到目标的ID值,取出所处改变前位置的值
            $sour_id = $changeid;
            $desc_value = $weighdata[$desc_id];
            $sour_value = $weighdata[$sour_id];
            //echo "移动的ID:{$sour_id}\n";
            //echo "替换的ID:{$desc_id}\n";
            $weighids = array();
            $temp = array_values(array_diff_assoc($ids, $sour));
            foreach ($temp as $m => $n) {
                if ($n == $sour_id) {
                    $offset = $desc_id;
                } else {
                    if ($sour_id == $temp[0]) {
                        $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
                    } else {
                        $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
                    }
                }
                $weighids[$n] = $weighdata[$offset];
                Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
            }
            $this->success();
        }
    }

    /**
     * 清空系统缓存
     */
    public function wipecache()
    {
        $type = $this->request->request("type");
        switch ($type) {
            case 'content' || 'all':
                rmdirs(CACHE_PATH, false);
                Cache::clear();
                if ($type == 'content')
                    break;
            case 'template' || 'all':
                rmdirs(TEMP_PATH, false);
                if ($type == 'template')
                    break;
            case 'addons' || 'all':
                Service::refresh();
                if ($type == 'addons')
                    break;
        }

        \think\Hook::listen("wipecache_after");
        $this->success();
    }
    //选择商品
    //获取供应商
    public function shop(){
        $model = new Preproduct();
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()){
            $type=null;
            //设置过滤方法
            $this->request->filter(['strip_tags', 'htmlspecialchars']);

            //搜索关键词,客户端输入以空格分开,这里接收为数组
            $word = (array)$this->request->request("q_word/a");
            //当前页
            $page = $this->request->request("pageNumber");
            //分页大小
            $pagesize = $this->request->request("pageSize");
            //搜索条件
            $andor = $this->request->request("andOr", "and", "strtoupper");
            //排序方式
            $orderby = (array)$this->request->request("orderBy/a");
            //显示的字段
            $field = $this->request->request("showField");
            //主键
            $primarykey = $this->request->request("keyField");
            //主键值
            $primaryvalue = $this->request->request("keyValue");
            //搜索字段
            $searchfield = (array)$this->request->request("searchField/a");
            //自定义搜索条件
            $custom = (array)$this->request->request("custom/a");
            if($type == 1){
                $searchfield = array_merge($searchfield, ['position','userid']);
            }

            $order = [];
            foreach ($orderby as $k => $v) {
                $order[$v[0]] = $v[1];
            }
            $field = $field ? $field : 'name';
            //如果有primaryvalue,说明当前是初始化传值
            if ($primaryvalue !== null) {
                $where = [$primarykey => ['in', $primaryvalue]];
            } else {
                $where = function ($query) use ($word, $andor, $field, $searchfield, $custom,$type) {
                    $query->where("type", '=', 1);

                    $logic = $andor == 'AND' ? '&' : '|';
                    $searchfield = is_array($searchfield) ? implode($type == 1?'|':$logic, $searchfield) : $searchfield;

                    foreach ($word as $k => $v) {
                        $query->where(str_replace(',', $type == 1?'|':$logic, $searchfield), "like", "%{$v}%");
                    }
                    if ($custom && is_array($custom)) {
                        foreach ($custom as $k => $v) {
                            if($type == 1){
                                $query->where($k, '<>', $v);
                            }else{
                                $query->where($k, '=', $v);
                            }
                        }
                    }


                };
            }

            $list = [];
            $total = $model->where($where)->count();
            if ($total > 0) {

                $datalist = $model->where($where)
                    ->order($order)
                    ->page($page, $pagesize)
                    ->select();


                foreach ($datalist as $index => $item) {
                    unset($item['password'], $item['salt']);
                    if($type == 1){
                        $value = isset($item[$field]) ? $item[$field] : '';
                        $value .=isset($item['position']) ? ' '.$item['position'] : '';
                        $value .=isset($item['userid']) ? '-'.$item['userid'] : '';
                        $list[] = [
                            $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                            $field      => $value
                        ];
                    }else{

                        $list[] = $item;
                        $list[$index]['cname'] = $item['cname'];
                        $list[$index]['className']=$this->getName($item['class_text']);

                    }
                }
            }
            //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
            return json(['list' => $list, 'total' => $total]);
        }

    }

    //选择商品成品
    //获取供应商
    public function shops(){
        $model = new Preproduct();
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()){
            $type=null;
            //设置过滤方法
            $this->request->filter(['strip_tags', 'htmlspecialchars']);

            //搜索关键词,客户端输入以空格分开,这里接收为数组
            $word = (array)$this->request->request("q_word/a");
            //当前页
            $page = $this->request->request("pageNumber");
            //分页大小
            $pagesize = $this->request->request("pageSize");
            //搜索条件
            $andor = $this->request->request("andOr", "and", "strtoupper");
            //排序方式
            $orderby = (array)$this->request->request("orderBy/a");
            //显示的字段
            $field = $this->request->request("showField");
            //主键
            $primarykey = $this->request->request("keyField");
            //主键值
            $primaryvalue = $this->request->request("keyValue");
            //搜索字段
            $searchfield = (array)$this->request->request("searchField/a");
            //自定义搜索条件
            $custom = (array)$this->request->request("custom/a");
            if($type == 1){
                $searchfield = array_merge($searchfield, ['position','userid']);
            }

            $order = [];
            foreach ($orderby as $k => $v) {
                $order[$v[0]] = $v[1];
            }
            $field = $field ? $field : 'name';
            //如果有primaryvalue,说明当前是初始化传值
            if ($primaryvalue !== null) {
                $where = [$primarykey => ['in', $primaryvalue]];
            } else {
                $where = function ($query) use ($word, $andor, $field, $searchfield, $custom,$type) {
                    $query->where("type", '=', 2);

                    $logic = $andor == 'AND' ? '&' : '|';
                    $searchfield = is_array($searchfield) ? implode($type == 1?'|':$logic, $searchfield) : $searchfield;

                    foreach ($word as $k => $v) {
                        $query->where(str_replace(',', $type == 1?'|':$logic, $searchfield), "like", "%{$v}%");
                    }
                    if ($custom && is_array($custom)) {
                        foreach ($custom as $k => $v) {
                            if($type == 1){
                                $query->where($k, '<>', $v);
                            }else{
                                $query->where($k, '=', $v);
                            }
                        }
                    }


                };
            }

            $list = [];
            $total = $model->where($where)->count();
            if ($total > 0) {

                $datalist = $model->where($where)
                    ->order($order)
                    ->page($page, $pagesize)
                    ->select();


                foreach ($datalist as $index => $item) {
                    unset($item['password'], $item['salt']);
                    if($type == 1){
                        $value = isset($item[$field]) ? $item[$field] : '';
                        $value .=isset($item['position']) ? ' '.$item['position'] : '';
                        $value .=isset($item['userid']) ? '-'.$item['userid'] : '';
                        $list[] = [
                            $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                            $field      => $value
                        ];
                    }else{

                        $list[] = $item;
                        $list[$index]['cname'] = $item['cname'];
                        $info = collection($model->where("id in (".$item['bcp'].")")->select())->toArray();

                        $list[$index]['zifenlei']=$info;

                        $list[$index]['className']=$this->getName($item['class_text']);

                    }
                }
            }
            //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
            return json(['list' => $list, 'total' => $total]);
        }

    }

    /**
     * @param $goods_name selectpage 
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getgoods()
    {
        $model = new Preproduct();
        if ($this->request->isAjax()){
            $type=null;
            //设置过滤方法
            $this->request->filter(['strip_tags', 'htmlspecialchars']);

            //搜索关键词,客户端输入以空格分开,这里接收为数组
            $word = (array)$this->request->request("q_word/a");
            //当前页
            $page = $this->request->request("pageNumber");
            //分页大小
            $pagesize = $this->request->request("pageSize");
            //搜索条件
            $andor = $this->request->request("andOr", "and", "strtoupper");
            //排序方式
            $orderby = (array)$this->request->request("orderBy/a");
            //显示的字段
            $field = $this->request->request("showField");
            //主键
            $primarykey = $this->request->request("keyField");
            //主键值
            $primaryvalue = $this->request->request("keyValue");
            //搜索字段
            $searchfield = (array)$this->request->request("searchField/a");
            //自定义搜索条件
            $custom = (array)$this->request->request("custom/a");

            $order = [];
            foreach ($orderby as $k => $v) {
                $order[$v[0]] = $v[1];
            }
            $field = $field ? $field : 'name';
            //如果有primaryvalue,说明当前是初始化传值
            if ($primaryvalue !== null) {
                $where = [$primarykey => ['in', $primaryvalue]];
            } else {
                $where = function ($query) use ($word, $andor, $field, $searchfield, $custom,$type) {

                    $logic = $andor == 'AND' ? '&' : '|';
                    $searchfield = is_array($searchfield) ? implode($type == 1?'|':$logic, $searchfield) : $searchfield;

                    foreach ($word as $k => $v) {
                        $query->where(str_replace(',', $type == 1?'|':$logic, $searchfield), "like", "%{$v}%");
                    }
                    if ($custom && is_array($custom)) {
                        foreach ($custom as $k => $v) {
                            if($type == 1){
                                $query->where($k, '<>', $v);
                            }else{
                                $query->where($k, '=', $v);
                            }
                        }
                    }


                };
            }

            $list = [];
            $total = $model->where($where)->count();
            if ($total > 0) {
                $datalist = $model->where($where)
                    ->order($order)
                    ->page($page, $pagesize)
                    ->select();
                $datalist = collection($datalist)->toArray();
                foreach ($datalist as $index => $item) {
                    $list[] = $item;
                    $list[$index]['cname'] = $item['cname'].'/ '.($item['type']==1 ? "半成品" : '成品');
                }
            }
            //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
            return json(['list' => $list, 'total' => $total]);
        }
        return false;
    }
     /**
     *  selectpage 联动获取书籍信息
     * @param $agentName
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getSchoolBook($id)
    {
        $model = new \app\admin\model\base\School;
        if(!$school = $model->get(['id'=>$id]))
        {
            return json(['bookname' => '']);
        }
        return json(['bookname' => $school->book_id]);
    }
    /**
     *  selectpage 联动获取代理商信息
     * @param $agentName
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getAgentInfo($agentName)
    {
        $model = new Info();
        if(!$agent = $model->get(['agent_name'=>$agentName]))
        {
            return json(['consigneeTelephone' => '', 'consigneeAddress' => '', 'consignee' => '']);
        }
        return json(['consigneeTelephone' => $agent->agent_phone, 'consigneeAddress' =>$agent->province_text.$agent->city_text.$agent->area_text.$agent->address, 'consignee' => $agent->agent_contact]);
    }
     /**
     *  selectpage 联动获取分公司信息
     * @param $agentName
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getAgentFenInfo($depid)
    {
        $model = new Githouse();
        if(!$agent = $model->get(['dep'=>$depid]))
        {
            return json(['consigneeTelephone' => '', 'consigneeAddress' => '', 'consignee' => '']);
        }
        return json(['consigneeTelephone' => $agent->mobile, 'consigneeAddress' =>$agent->province_text.$agent->city_text.$agent->area_text.$agent->address, 'consignee' => $agent->lxr,'gname'=>$agent->gname]);
    }

    protected function getName($name){
        if (empty($name))return;
        $arr = explode(",",$name);

        $model = new Cate();
        $str=array();
        foreach ($arr as $v){
            $info = $model->field('name')->find($v);
            if ($info){
                $str[]=$info['name'];
            }
        }
        return implode(',',$str);
    }

    //获取供应商
    public function suppli(){
        $model = new Supplier();

        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()){
            if ($this->request->isAjax()){

                return $this->selectpage($model);

            }
        }
    }
    protected function selectpage($model = NULL,$type = NULL)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        if($type == 1){
            $searchfield = array_merge($searchfield, ['position','userid']);
        }

        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom,$type) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($type == 1?'|':$logic, $searchfield) : $searchfield;

                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $type == 1?'|':$logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if($type == 1){
                            $query->where($k, '<>', $v);
                        }else{
                            $query->where($k, '=', $v);
                        }
                    }
                }

            };
        }

        $list = [];
        $total = $model->where($where)->count();
        if ($total > 0) {

            $datalist = $model->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->select();


            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if($type == 1){
                    $value = isset($item[$field]) ? $item[$field] : '';
                    $value .=isset($item['position']) ? ' '.$item['position'] : '';
                    $value .=isset($item['userid']) ? '-'.$item['userid'] : '';
                    $list[] = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => $value
                    ];
                }else{
                    $list[] = $item;
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
    /*
        * 获取仓库分类，分2个类型，半成品，和成品，根据type来指定
        * */
    public function housecate(){
        $model = new Cate();
        $type = $this->request->get("type");
        $pid = $this->request->get("pid");
        $t = $this->request->get("t");
        if ($t==3 && empty($pid)){
            $this->success('', null, []);
        }

        if ($pid==0 && $type==2){
            $where['pid']=0;
            $where['id']=array("eq",216);

        }else{
            if ($pid==0 && $type==1){
                $where['id']=array("eq",226);

            }else{
                $where['pid']=array('eq',$pid);


                $where['type']=array('eq',$type);
            }

        }

        $list = Db::name('halt_cate')->where($where)->field('id as value,name')->select();

        $this->success('', null, $list);



    }
    /**
     * 读取分类数据,联动列表
     */
    public function category()
    {
        $type = $this->request->get('type');
        $pid = $this->request->get('pid');
        $where = ['status' => 'normal'];
        $categorylist = null;
        if ($pid !== '') {
            if ($type) {
                $where['type'] = $type;
            }
            if ($pid) {
                $where['pid'] = $pid;
            }
            $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
        }

        $this->success('', null, $categorylist);
    }

    /**
     * 读取分类数据,联动列表
     */
    public function cate()
    {
        $type = $this->request->get('type');
        $pid = $this->request->get('pid');
        $id = $this->request->get('id');

        $where = [];
        $categorylist = null;
        if ($pid !== '') {
            if ($type) {
                $where['type'] = $type;
            }

            $where['pid'] = $pid;
            if ($pid==0 ){
                if ($id!=null){
                    $where = "type=$type and pid=0 and id in(8,325,334,342,422,464,489)";
                }else{
                    $where['pid']=0;
                    $where['id']=array("neq",8);

                }


                $categorylist = Db::name('halt_cate')->where($where)->field('id as value,name')->order('id desc')->select();

            }else{
                $categorylist = Db::name('halt_cate')->where($where)->field('id as value,name')->order('id desc')->select();

            }
        }

        $this->success('', null, $categorylist);
    }

    /**
     * 读取省市区数据,联动列表
     */
    public function area()
    {
        $province = $this->request->get('province');
        $city = $this->request->get('city');
        $where = ['pid' => 0, 'level' => 1];
        $provincelist = null;
        if ($province !== '') {
            if ($province) {
                $where['pid'] = $province;
                $where['level'] = 2;
            }
            if ($city !== '') {
                if ($city) {
                    $where['pid'] = $city;
                    $where['level'] = 3;
                }
                $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
            }
        }
        $this->success('', null, $provincelist);
    }
     /**
     * 读取省市区数据,联动列表
     */
    public function area_2()
    {
        $province = $this->request->get('shen');
        $city = $this->request->get('shi');
        $where = ['pid' => 0, 'level' => 1];
        $provincelist = null;
        if ($province !== '') {
            if ($province) {
                $where['pid'] = $province;
                $where['level'] = 2;
            }
            if ($city !== '') {
                if ($city) {
                    $where['pid'] = $city;
                    $where['level'] = 3;
                }
                $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
            }
        }
        $this->success('', null, $provincelist);
    }
    /**
     * 读取年 周
     */
    public function year(){
        $num = $this->request->get('num');
        $year = $this->request->get('year');
        $start_year = 2018;
        $yearArr = [];
        if ($year !== '') {
            if($year){
                $week = GetYearWeek($year);
                $a = 0;
                foreach($week as $key=>$val){
                    $yearArr[$a]['value'] = $val[0].','.$val[1];
                    $yearArr[$a]['name'] = '第'.$key.'周'.','.$yearArr[$a]['value'];
                    $a++;
                }
            }
            if($num){
                $a = 0;
                for($i=$start_year; $i<=$start_year+$num; $i++){
                    $yearArr[$a]['value'] = $i;
                    $yearArr[$a]['name'] = $i.'年';
                    $a++;
                }
            }
        }
        $this->success('', null, $yearArr);
    }

    /**
     * 获取周、场次、学校
     */
    public function week() {
        $department = $this->request->get('department');
        $week_id = $this->request->get("week_id");
        $season_id = $this->request->get("season_id");
        $school_id = $this->request->get("school_id");
        // $where = ['department' => $department,'status'=>3];
        $where = ['department' => $department];
        $provincelist = null;
        if ($department !== '') {
            $provincelist = Db::name('finance_extract_week')->where($where)->field('id as value,name')->select();
            if ($season_id && $week_id) {
                $where = ['season_id' => $season_id,'extract_week'=>$week_id];
                $provincelist = Db::name('finance_extract_school')->where($where)->field('id,school_id')->select();
                $provincelist = array_map(function($vss){return ['value'=>$vss['id'].'-'.$vss['school_id'],'name'=>TableField('DataSchool','name',$vss['school_id'])];}, $provincelist);
            }else{
                if ($week_id) {
                    $where = ['extract_week' => $week_id];
                    $provincelist = Db::name('finance_extract_season')->where($where)->field('id as value,name')->select();
                }
            }
        }

        $this->success('', null, $provincelist);
    }

    /**
     * 查询数据来源
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ManSelect()
    {
        $this->model = new \app\admin\model\Management;
        $result = $this->model->field('source')->group('source')->select();

        foreach ($result as $value)
        {
            $arr[$value['source']] =$value['source'];
        }
        $arr = array_filter($arr);
        return json($arr);
    }

    /**
     *  查询产品分类
     * @return \think\response\Json
     */
    public function product()
    {
        $data = json_decode(Config::get('wxproduct')['type'],true);
        if($key = $this->request->request('keyValue')){
            $row = null;
            foreach ($data as $value)
            {
                if($value['id'] == $key)
                {
                    $row = $value;
                }
            }
            unset($data);
            $list = ['list'=> $row];
            $arr = array_filter($list);
            return json($arr);
        }
        $list['total'] = count($data);
        $list = ['list'=>$data];
        $arr = array_filter($list);
        return json($arr);
    }

    /**
     * 查询产品单位分类
     * @return \think\response\Json
     */
    public function dw()
    {
        if($this->request->request('keyValue') == 1){
            $list = ['list'=>
                ['id'=>1,'name'=>'单']
            ];
            $arr = array_filter($list);
            return json($arr);
        }
        if($this->request->request('keyValue') == 2){
            $list = ['list'=>
                ['id'=>2,'name'=>'套']
            ];
            $arr = array_filter($list);
            return json($arr);
        }
        $list['total'] = 2;
        $list = ['list'=> [
             ['id'=>1,'name'=>'单'],
            ['id'=>2,'name'=>'套']
        ]];
        $arr = array_filter($list);
        return json($arr);
    }

}